import { Message, Loading, MessageBox } from 'element-ui';
import axios from 'axios'

//以下是无需登录的发送ajax请求的公用函数
import Qs from 'qs';
var defaultAjaxOptions = {
    loading: true,
    method: 'GET',
    paramsSerializer: function (params) {
        return Qs.stringify(params, { arrayFormat: 'brackets' })
    },
    jsonp: false,
    jsonpCallback: 'callback',
    transformJsonp: function (content, callbackName) {
        var fun = new Function('var ' + callbackName + '=function(data){return data;}; return ' + callbackName + '(' + content + ');');
        return fun();
    }
};

var addCommonParams = (ops) => {
    var commonParams = {
        platId: '501',
        headver: '1.3.0.11',
        headtime: new Date().getTime()
    }
    if (ops.params && ops.params.para) {
        ops.params.para = typeof ops.params.para === 'string' ? JSON.parse(ops.params.para) : ops.params.para;
        if (typeof ops.params.para === 'object') {
            ops.params.para = JSON.stringify(Object.assign({}, commonParams, ops.params.para));
        }
    } else if (ops.data && ops.data.para) {
        ops.data.para = typeof ops.data.para === 'string' ? JSON.parse(ops.data.para) : ops.data.para;
        if (typeof ops.data.para === 'object') {
            ops.data.para = JSON.stringify(Object.assign({}, commonParams, ops.data.para));
        }
    }

    if (ops.method === 'GET' && (!ops.params || (ops.params && !ops.params.para))) {
        ops.params = ops.params || {};
        ops.params.para = JSON.stringify(commonParams);
    }
}
export default options => {
    var ops = Object.assign({}, defaultAjaxOptions, options),
        loadingInc;

    addCommonParams(ops);
    if (ops.jsonp) {
        ops.method = "GET";
        ops.responseType = "text";

        var callbackName = 'axios' + new Date().getTime();
        if (typeof ops.params === 'string') {
            ops.params += '&' + ops.jsonpCallback + "=" + callbackName;
        } else {
            ops.params = ops.params || {};
            ops.params[ops.jsonpCallback] = callbackName;
        }
        ops.transformResponse = [function (content) {
            return ops.transformJsonp(content, callbackName);
        }, function (error) {
            return error;
        }]
    }
    if (ops.loading) {
        loadingInc = Loading.service({ fullscreen: true });
    }
    return axios(ops).then(res => {
        if (loadingInc) {
            loadingInc.close();
        }
        return res;
    }).catch(error => {
        if (loadingInc) {
            loadingInc.close();
        }
        return error;
    });
}